<script setup>
import { ref, onMounted, watch, nextTick } from 'vue'
import { Promotion, ArrowDown, ArrowUp } from '@element-plus/icons-vue'
import chatAvatar from '@/assets/img/lg.png'
import userAvatar from '@/assets/img/fufu.jpg'
import chat from '@/views/enterprise/service/chat_fun'
import { downloadTextAsFile } from './service/method'
import { useEnterpriseStore } from '@/stores'
import loading from '@/views/enterprise//service/state.js' // loding状态管理文件
import { setLoading } from '@/views/enterprise//service/state.js' // loding状态管理文件

const enterpriseStore = useEnterpriseStore()

let baseList = ref([])
const docsList = ref([])
onMounted(async () => {
  baseList.value = await chat.getBaseList() //base列表信息
  docsList.value = await chat.getDocsList('defaultBase') //docs列表信息
})
/*对话模式&base菜单相关 */
const modeOpen = ref(false)
const baseOpen = ref(false)
const selectedMode = ref('知识库对话') //追踪对话模型
const selectedBase = ref(enterpriseStore.knowledge_base) //追踪知识库名  defaultBase默认知识库
const selectMode = (mode) => {
  selectedMode.value = mode
  modeOpen.value = false
}
/*刷新知识库*/
const isView = ref(false)
const refreshBase = () => {
  isView.value = true
  chat.updateDocs(selectedBase.value)
  isView.value = false
}
const selectBase = async (base) => {
  selectedBase.value = base
  docsList.value = await chat.getDocsList(base) //docs列表信息
  baseOpen.value = false
}
const handleClickOutside = (event) => {
  const modeOptions = event.target.querySelector('.mode-options')
  const baseOptions = event.target.querySelector('.base-options')
  if (!modeOptions || !modeOptions.contains(event.target)) {
    modeOpen.value = false
  }
  if (!baseOptions || !baseOptions.contains(event.target)) {
    baseOpen.value = false
  }
}
/*chat 相关*/
let chatList = ref([]) //chat对话信息列表
const userQuery = ref('') //用户输入
//追加信息
const appendMessage = async (sender, query) => {
  const isUser = sender === 'user'
  // 创建包含头像和对话内容的元素
  if (isUser) {
    chatList.value.push({ sender: 'user', msg: query, imgSrc: userAvatar }) //添加用户输入
  } else {
    chatList.value.push({ sender: 'chat', msg: query, imgSrc: chatAvatar }) //添加chat回复
  }
  await nextTick() // 等待 DOM chatRef更新
  scrollToBottom()
}
const sendQuery = async () => {
  appendMessage('user', userQuery.value)
  setLoading(true)
  let tempQuery = userQuery.value
  userQuery.value = ''
  const text = await chat.chatAI(
    tempQuery,
    selectedMode.value,
    selectedBase.value
    // history.value
  )
  setLoading(false)
  appendMessage('assistant', text)
}
//监听selectedMode
watch(selectedMode, () => {
  chatList.value = []
})
const chatRef = ref()
// 监听 chatRef 更新滚动到容器底部
const scrollToBottom = () => {
  if (chatRef.value) {
    chatRef.value.scrollTop = chatRef.value.scrollHeight
  }
}
/*导出聊天记录 */
const exportChat = () => {
  let conversation = ''
  for (let i = 0; i < chatList.value.length; i++) {
    const role = chatList.value[i].sender
    const chatMessage = chatList.value[i].msg
    if (chatMessage) {
      conversation += role + ':' + chatMessage + '\n'
    }
  }
  downloadTextAsFile('conversation.txt', conversation) // 下载文件名为'conversation.txt'的文件
}
</script>
<template>
  <layout-com title="智能助手">
    <!-- 主体部分 -->
    <el-container class="chat-container" @click="handleClickOutside">
      <el-aside class="settings-part">
        <div class="container">
          <div class="text">请选择对话模式 :</div>
          <div class="current" @click.stop="modeOpen = true">
            {{ selectedMode }}
            <span class="icon">
              <el-icon v-if="modeOpen"><ArrowUp /></el-icon>
              <el-icon v-else><ArrowDown /></el-icon>
            </span>
          </div>
          <div class="mode-options options" v-show="modeOpen">
            <div class="mode option" @click="selectMode('Chat对话')">
              Chat对话
            </div>
            <div class="mode option" @click="selectMode('知识库对话')">
              知识库对话
            </div>
          </div>
        </div>
        <br />
        <el-divider />
        <el-divider />
        <div v-if="selectedMode === '知识库对话'">
          <div class="container">
            <div class="text">请选择知识库 :</div>
            <div class="current" @click.stop="baseOpen = true">
              {{ selectedBase }}
              <span class="icon">
                <el-icon v-if="baseOpen"><ArrowUp /></el-icon>
                <el-icon v-else><ArrowDown /></el-icon>
              </span>
            </div>

            <div class="base-options options" v-show="baseOpen">
              <div
                class="base option"
                v-for="(base, index) in baseList"
                :key="index"
                @click="selectBase(base)"
              >
                <span class="base-text">{{ base }}</span>
              </div>
            </div>
          </div>
          <div class="container">
            <div class="text">本知识库内文件 :</div>
            <div class="docs-loding" v-if="isView === true"></div>
            <div class="docs-options options">
              <div class="docs" v-for="(docs, index) in docsList" :key="index">
                <span class="docs-text">{{ docs }}</span>
              </div>
            </div>
          </div>
          <button class="refresh-btu btu" @click="refreshBase">
            更新知识库
          </button>
        </div>

        <el-button class="export-btu btu" @click="exportChat"
          ><span>Export-Chat-History</span></el-button
        >
      </el-aside>
      <el-container>
        <el-main class="chat-part">
          <div ref="chatRef" class="chatbox">
            <div
              v-for="(item, index) in chatList"
              :key="index"
              class="message-container"
            >
              <img class="avatar" :src="item.imgSrc || url" alt="" />
              <div class="chat-message">{{ item.msg }}</div>
            </div>
            <div
              v-loading="loading"
              element-loading-text="正在努力思考..."
              element-loading-background="transparent"
              :element-loading-spinner="svg"
              element-loading-svg-view-box="-10, -10, 50, 50"
              class="loadSvg"
            ></div>
          </div>
        </el-main>
        <div class="space"></div>
        <el-footer class="query-part">
          <textarea
            v-model="userQuery"
            @keyup.enter="sendQuery"
            class="send-query"
            cols="70"
          ></textarea>
          <span class="send-btu btu" @click="sendQuery">
            <el-icon size="2em" color="#ffff">
              <Promotion />
            </el-icon>
          </span>
        </el-footer>
      </el-container>
    </el-container>
  </layout-com>
</template>

<style lang="scss" scoped>
.chat-container {
  height: 75vh;
  position: relative;
  border-radius: 10px;
  .settings-part {
    position: relative;
    width: 220px;
    background-color: #fdfcff;
    border-radius: 5px;
    .container {
      position: relative;
      margin-top: 20px;
      width: 180px;
      left: 20px;
    }
    .docs-loding {
      position: relative;
      top: +100px;
      left: +70px;
      width: 30px;
      height: 30px;
      border: 2px solid #000;
      border-top-color: transparent;
      border-radius: 100%;
      animation: circle infinite 0.75s linear;
      z-index: 1;
      // 转转转动画
      @keyframes circle {
        0% {
          transform: rotate(0);
        }
        100% {
          transform: rotate(360deg);
        }
      }
    }

    .mode-options {
      z-index: 1;
    }
    .base-options {
      max-height: 80px;
      overflow-y: scroll;
      z-index: 1;
    }
    .docs-options {
      height: 150px;
      overflow-y: scroll;
      z-index: 0;
    }
    .export-btu {
      position: relative;
      height: 30px;
      left: 25px;
      top: 40px;
      z-index: 0;
    }
    .refresh-btu {
      position: relative;
      height: 25px;
      top: 5px;
      left: 100px;
    }
    .options {
      position: absolute;
      top: calc(100% + 1px);
      left: 0;
      right: 0;
      background-color: #fff;
      border: 1px solid #ddd;
      box-shadow: 8px 8px 8px rgba(56, 51, 51, 0.15);
      border-radius: 15px;
      padding: 10px;
      display: flex;
      flex-direction: column;
    }
    .docs-options {
      position: relative;
      left: 15px;
      width: 125px;
      .docs-text {
        font-size: 12px;
      }
    }
    .option {
      padding: 5px;
      border-radius: 5px;
      cursor: pointer;
      &:hover {
        background-color: rgb(153, 173, 199);
      }
    }
    .current {
      padding: 10px;
      border: 1px solid #ddd;
      border-radius: 15px;
      cursor: pointer;
    }
    .icon {
      display: inline-block;
      position: absolute;
      right: 10px;
    }
    .text {
      font-size: 15px;
      margin-left: 5px;
      margin-bottom: 10px;
      color: #666666;
      font-weight: bold;
    }
  }
  .chat-part {
    position: relative;
    display: flex;
    flex-direction: column;
    width: 850px;
    height: 500px;
    left: 100px;
    background-color: #fdfcff;
    border-radius: 10px;
    .chatbox {
      border: 1px solid #ccc;
      border-radius: 3px;
      overflow-y: scroll;
      padding: 10px;
      height: 440px;
      .message-container {
        position: relative;
        display: flex;
        padding: 10px;

        .avatar {
          display: inline-block;
          width: 50px;
          height: 50px;
          border-radius: 50%;
          margin-right: 20px;
          .avatar img {
            width: 50px;
            height: 50px;
            border-radius: 50%;
          }
        }
        .chat-message {
          border-radius: 5px;
          display: inline-block;
          background-color: rgb(149, 170, 198);
          color: #333;
          padding: 10px;
        }
      }
      .loadSvg {
        width: 100px;
        height: 50px;
      }
    }
  }
  .space {
    height: 20px;
  }
  .query-part {
    position: relative;
    height: 80px;
    width: 850px;
    left: 100px;
    border: 2px solid #ffffff;
    border-radius: 5px;
    background-color: #fdfdfd;
    .send-query {
      width: 92%;
      height: 80%;
      margin-top: 10px;
      padding: 10px;
      font-size: 18px;
      white-space: pre-wrap; /* 保留空格和换行符 */
      overflow: hidden; /* 隐藏滚动条 */
      word-wrap: break-word;
      word-break: break-all; /* 单词内换行*/
      border: none;
      outline: none; /* 移除边框 */
      box-sizing: border-box; /* 包含边框和内边距在宽度内 */
    }
    .send-btu {
      position: absolute;
      width: 50px;
      height: 40px;
      right: 10px;
      bottom: 10px;
    }
    .send-btu:hover {
      transform: scale(1.2); /* 放大 1.2 倍 */
    }
    .query-part:focus-within {
      border: 2px solid rgb(2, 1, 25); /* 当子元素获得焦点时，为.send-box添加边框 */
      box-shadow: 0 0 10px rgba(15, 15, 17, 0.5);
    }
  }
}
/* 修改滚动条颜色为灰色 */
::-webkit-scrollbar {
  width: 8px;
  background-color: #f3f3f3;
}
/* 修改滚动条滑块颜色 */
::-webkit-scrollbar-thumb {
  background-color: rgb(149, 170, 198);
  border-radius: 3px;
}
.btu {
  color: #ffffff;
  text-align: center;
  border-radius: 15px;
  background: linear-gradient(to right, #354152, #6582aa);
}
.btu:hover {
  filter: brightness(1.5); /* 增加亮度 1.5 倍 */
}
</style>
